package cn.e4j.modular.erp.v2.util;

import cn.e4j.modular.erp.v2.entity.*;
import cn.e4j.modular.erp.v2.entity.base.BaseRequestEntity;
import cn.e4j.modular.erp.v2.entity.base.BaseResponseEntity;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

/**
 * T100-v2-接口调用工具类
 * Created by yuan_rz on 2019-03-18.
 */
public class T100Util {
    private static String ERP_WEBSERVICE_URL = "topprd_erp_webservice_url";
    public static BaseResponseEntity connect(BaseRequestEntity baseRequestEntity, Class baseResponseEntityClass){
        //返回参数
        BaseResponseEntity baseResponseEntity = null;
        //接口地址
        String targetURL = ERP_WEBSERVICE_URL;
        //调用接口
        HttpURLConnection httpConnection = null;
        try {
            URL targetUrl = new URL(targetURL);
            httpConnection = (HttpURLConnection) targetUrl
                    .openConnection();
            httpConnection.setDoInput(true);
            httpConnection.setDoOutput(true);//允许写
            httpConnection.setRequestMethod("POST");
//            httpConnection.setRequestProperty("Pragma:", "no-cache");
//            httpConnection.setRequestProperty("Cache-Control", "no-cache");
            httpConnection.setRequestProperty("Content-Type",
                    "application/json;charset=GBK");
            httpConnection.setConnectTimeout(6000);//很重要，设置超时时间
            httpConnection.connect();//真正的连接服务器
            String input = JSONObject.toJSON(baseRequestEntity).toString();
            OutputStream outputStream = httpConnection.getOutputStream();
            outputStream.write(input.getBytes());
            outputStream.flush();
            if (httpConnection.getResponseCode() != 200) {
                baseResponseEntity.payload.std_data.execution.code = String.valueOf(httpConnection.getResponseCode());
                baseResponseEntity.payload.std_data.execution.description = "httpConnection errcode" + httpConnection.getResponseCode();
                return baseResponseEntity;
            }else{
                StringBuffer temp = new StringBuffer();
                InputStream in = new BufferedInputStream(httpConnection.getInputStream());
                Reader rd = new InputStreamReader(in,"GBK");//服务器返回的也是GBK编码格式的数据。

                BufferedReader responseBuffer = new BufferedReader(
                        new InputStreamReader((httpConnection.getInputStream()),
                                "UTF-8"));
                String output;
                StringBuffer result = new StringBuffer();
                while ((output = responseBuffer.readLine()) != null) {
                    result.append(output);
                }
                baseResponseEntity = (BaseResponseEntity)JSON.parseObject(result.toString(),baseResponseEntityClass);
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            httpConnection.disconnect();
        }
        return baseResponseEntity;
    }
    public static OrderCreateResponseEntity genOrder(OrderCreateRequestEntity orderCreateRequestEntity, String ent, String site) {
        String targetURL = ERP_WEBSERVICE_URL;
        orderCreateRequestEntity.datakey.EntId = ent;
        orderCreateRequestEntity.datakey.CompanyId = site;
        if(targetURL.contains("topprd")){
            orderCreateRequestEntity.service.ip = targetURL.replace("http://","")
                    .replace("/wstopprd/ws/r/awsp920","");
        }else{
            orderCreateRequestEntity.service.ip = targetURL.replace("http://","")
                    .replace("/wstoptst/ws/r/awsp920","");
        }
        orderCreateRequestEntity.service.name = "order.create";
        if(targetURL.contains("topprd")){
            orderCreateRequestEntity.service.id = "topprd";
        }else{
            orderCreateRequestEntity.service.id = "toptst";
        }
        orderCreateRequestEntity.payload.std_data.parameter.enterprise_no = ent;
        orderCreateRequestEntity.payload.std_data.parameter.site_no = site;
        return (OrderCreateResponseEntity)connect(orderCreateRequestEntity,OrderCreateResponseEntity.class);
    }
    public static ShipmentCreateResponseEntity genShipment(ShipmentCreateRequestEntity shipmentCreateRequestEntity, String ent, String site, Boolean chekInventory) {
        String targetURL = ERP_WEBSERVICE_URL;
        shipmentCreateRequestEntity.datakey.EntId = ent;
        shipmentCreateRequestEntity.datakey.CompanyId = site;
        if(targetURL.contains("topprd")){
            shipmentCreateRequestEntity.service.ip = targetURL.replace("http://","")
                    .replace("/wstopprd/ws/r/awsp920","");
        }else{
            shipmentCreateRequestEntity.service.ip = targetURL.replace("http://","")
                    .replace("/wstoptst/ws/r/awsp920","");
        }
        if(chekInventory){
            shipmentCreateRequestEntity.service.name = "shipping.create";
        }else{
            shipmentCreateRequestEntity.service.name = "shipping.create.nochekinventory";
        }
        if(targetURL.contains("topprd")){
            shipmentCreateRequestEntity.service.id = "topprd";
        }else{
            shipmentCreateRequestEntity.service.id = "toptst";
        }
        shipmentCreateRequestEntity.payload.std_data.parameter.enterprise_no = ent;
        shipmentCreateRequestEntity.payload.std_data.parameter.site_no = site;
        return (ShipmentCreateResponseEntity)connect(shipmentCreateRequestEntity,ShipmentCreateResponseEntity.class);
    }

    /**
     * 对账单查询服务
     * @param getBillRequestEntity
     * @param ent
     * @param site
     * @return
     */
    public static GetBillResponseEntity getBillResponseEntity(GetBillRequestEntity getBillRequestEntity, String ent, String site) {
        String targetURL = ERP_WEBSERVICE_URL;
        getBillRequestEntity.datakey.EntId = ent;
        getBillRequestEntity.datakey.CompanyId = site;
        if(targetURL.contains("topprd")){
//            getBillRequestEntity.service.ip = targetURL.replace("http://",targetURL)
//                    .replace("/wstopprd/ws/r/awsp900",targetURL);
//            getBillRequestEntity.service.ip="http://192.168.100.101/wstopprd/ws/r/awsp920"; //内网
            getBillRequestEntity.service.ip="http://116.236.85.134:888/wstopprd/ws/r/awsp920"; //外网
            ERP_WEBSERVICE_URL=getBillRequestEntity.service.ip;
        }else{
            getBillRequestEntity.service.ip = targetURL.replace("http://","")
                    .replace("/wstoptst/ws/r/awsp920","");
        }
        getBillRequestEntity.service.name = "fxweb.dz.query";
        if(targetURL.contains("topprd")){
            getBillRequestEntity.service.id = "topprd";
        }else{
            getBillRequestEntity.service.id = "toptst";
        }
//        getBillRequestEntity.payload.std_data.parameter.enterprise_no = ent;
//        getBillRequestEntity.payload.std_data.parameter.site_no = site;
        return (GetBillResponseEntity)connect(getBillRequestEntity,GetBillResponseEntity.class);
    }
}
